package com.enzo.prms.task.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.quartz.JobDataMap;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.enzo.prms.common.constant.Constant;
import com.enzo.prms.common.exception.base.ServiceException;
import com.enzo.prms.common.util.DateUtil;
import com.enzo.prms.common.util.StringUtil;
import com.enzo.prms.job.TaskRemind;
import com.enzo.prms.job.manager.JobManager;
import com.enzo.prms.task.model.Task;
import com.enzo.prms.task.model.Tlist;
import com.enzo.prms.task.service.TaskService;
import com.enzo.prms.task.service.TlistService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

@Component("taskAction")
@Scope("prototype")
public class TaskAction extends ActionSupport implements ModelDriven<Task> {
	private static final long serialVersionUID = -3970759771676359949L;
	private static final Logger logger=Logger.getLogger(TaskAction.class);
	/**推迟1天 */
	private static final int DELAY_DAY=1;
	private Task task=new Task();
	private List<Tlist> tlists;
	private List<Task> tasks;
	private String tlistId;
	private String tlistName;
	private String updateType;
	private String taskIds;
	private String updateTaskId;
	private String updateTaskName;
	private String updateTaskStartTime;
	private String taskPriority;
	private String updateTaskNote;
	private Map<String,Object> jsonMap=new HashMap<String, Object>();
	
	@Resource
	private TaskService taskService;
	@Resource
	private TlistService tlistService;
	@Resource
	private JobManager jobManager;

	public String index(){
//		String hql="from Tlist t where t.flag=1 order by t.createTs desc";
//		tlists=tlistService.getListByHQL(hql, null);

		DetachedCriteria criteria=DetachedCriteria.forClass(Tlist.class);
		criteria.add(Restrictions.eq("flag", 1)).addOrder(Order.asc("createTs"));
//		criteria.add(Property.forName("flag").eq(1)).addOrder(Order.asc("createTs"));
		tlists=tlistService.getListByCriteria(criteria);
		
		return "index";
	}
	             
	public String searchTask() {
		logger.info(tlistName);
		Tlist tlist = tlistService.getTlistByName(tlistName);
		if (tlist != null) {
//			String hql="from Task t where t.list.id=:listId order by t.priority";
//			Map<String, Object> param=new HashMap<String, Object>();
//			param.put("listId", tlist.getId());
//			tasks = taskService.getListByHQL(hql, param);
			
			DetachedCriteria criteria=DetachedCriteria.forClass(Task.class);
			criteria.add(Restrictions.eq("list.id", tlist.getId())).add(Restrictions.isNull("status")).addOrder(Order.asc("priority"));
//			criteria.createAlias("list","lt").add(Restrictions.eq("lt.id", tlist.getId())).addOrder(Order.asc("priority"));
			tasks=taskService.getListByCriteria(criteria);
		}
		return "search_task";
	}
	
	public String createTask() {
		Tlist list = tlistService.getTlistByName(tlistName);
		task.setList(list);
		taskService.save(task);
		setMessage(Constant.MSG_CREATE_SUCCESS);
		return SUCCESS;
	}
	
	public String deleteTask(){
		String[] tasks = StringUtil.splitString(taskIds, "_");
		String hql = "delete Task t where t.id in(:taskIds)";
		Map<String, Object> params = new HashMap<String, Object>();
		List<Integer> list = new ArrayList<Integer>();
		for (String taskId : tasks) {
			list.add(Integer.parseInt(taskId));
			jobManager.removeJob(taskId);
		}
		params.put("taskIds", list);
		taskService.executeByHql(hql, params);
		setMessage(Constant.MSG_DELETE_SUCCESS);
		return SUCCESS;
	}
	
	public String delayTask(){
		String[] idArr=StringUtil.splitString(taskIds, "_");
		List<Integer> idList=new ArrayList<Integer>();
		for(String id:idArr){
			idList.add(Integer.parseInt(id));
		}
		DetachedCriteria criteria=DetachedCriteria.forClass(Task.class);
		criteria.add(Restrictions.in("id", idList));
		tasks=taskService.getListByCriteria(criteria);
		
		for(Task task:tasks){
			String jobName=getJobName(task);
			Date startTs=task.getStartTs();
			Date now=DateUtil.getDate();
			if(startTs==null){
				task.setStartTs(now);
			}else{
				int dayDiff=DateUtil.getDayDiff(now, startTs);
				Date newDate;
				if(dayDiff>1){
					newDate=now;
				}else{
					newDate=DateUtil.getAnotherDate(startTs, DELAY_DAY);
				}
				task.setStartTs(newDate);
			}
			taskService.update(task);
			Map<String, Object> data=new HashMap<String, Object>();
			data.put("detail",task.getTaskName()+"/"+task.getList().getListName());
			jobManager.schedulerJob(jobName, task.getStartTs(),data, TaskRemind.class);
			setMessage(Constant.MSG_DELAY_SUCCESS);
		}
		return SUCCESS;
	}
	
	public String completeTask() {
		String[] tasks = StringUtil.splitString(taskIds, "_");
		String hql = "update Task t set t.status='1' where t.id in(:taskIds)";
		Map<String, Object> params = new HashMap<String, Object>();
		List<Integer> list = new ArrayList<Integer>();
		for (String taskId : tasks) {
			list.add(Integer.parseInt(taskId));
			jobManager.removeJob(taskId);
		}
		params.put("taskIds", list);
		taskService.executeByHql(hql, params);
		setMessage(Constant.MSG_UPDATE_SUCCESS);
		return SUCCESS;
	}
	
	public String moveTask(){
		String[] tasks = StringUtil.splitString(taskIds, "_");
		String hql = "update Task t set t.list.id=:tlistId where t.id in(:taskIds)";
		Map<String, Object> params = new HashMap<String, Object>();
		List<Integer> list = new ArrayList<Integer>();
		for (String taskId : tasks) {
			list.add(Integer.parseInt(taskId));
		}
		params.put("taskIds", list);
		params.put("tlistId", Integer.parseInt(tlistId));
		taskService.executeByHql(hql, params);
		setMessage(Constant.MSG_MOVE_SUCCESS);
		return SUCCESS;
	}
	
	public String updateTask(){
		//更新任务优先级
		if("updatePriority".equals(updateType)&&StringUtil.isNotEmpty(taskIds)){
			String[] tasks=StringUtil.splitString(taskIds, "_");
			String hql = "update Task t set t.priority=:tPriority where t.id in(:taskIds)";
			Map<String, Object> params = new HashMap<String, Object>();
			List<Integer> list = new ArrayList<Integer>();
			for (String taskId : tasks) {
				list.add(Integer.parseInt(taskId));
			}
			params.put("tPriority", taskPriority);
			params.put("taskIds", list);
			taskService.executeByHql(hql, params);
		}else if("updateName".equals(updateType)&&StringUtil.isNotEmpty(updateTaskId)&&StringUtil.isNotEmpty(updateTaskName)){
			Task task=taskService.load(Integer.parseInt(updateTaskId));
			if (task != null) {
				task.setTaskName(updateTaskName);
				taskService.update(task);
				setMessage(Constant.MSG_UPDATE_SUCCESS);
			}
			Map<String, Object> data=new HashMap<String, Object>();
			data.put("detail",task.getTaskName()+"/"+task.getList().getListName());
			jobManager.schedulerJob(getJobName(task), task.getStartTs(),data, TaskRemind.class);
		}else if ("updateTaskStartTime".equals(updateType)&&StringUtil.isNotEmpty(updateTaskId)) {
			Task task=taskService.load(Integer.parseInt(updateTaskId));
			task.setStartTs(DateUtil.praseDate(updateTaskStartTime,""));
			taskService.update(task);
			Map<String, Object> data=new HashMap<String, Object>();
			data.put("detail",task.getTaskName()+"/"+task.getList().getListName());
			jobManager.schedulerJob(getJobName(task), task.getStartTs(),data, TaskRemind.class);
		}else if ("updateTaskNote".equals(updateType)&&StringUtil.isNotEmpty(updateTaskId)) {
			String hql="update Task t set t.note=:note where t.id='"+updateTaskId+"'";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("note", updateTaskNote);
			taskService.executeByHql(hql, params);
		}
		setMessage(Constant.MSG_UPDATE_SUCCESS);
		return SUCCESS;
	}
	
	private String getJobName(Task task){
		String jobName=task.getId()+"";
		return jobName;
	}
	
	public void setMessage(String msg){
		jsonMap.clear();
		jsonMap.put("msg",msg);
	}
	
	@Override
	public Task getModel() {
		return task;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public TlistService getTlistService() {
		return tlistService;
	}
	
	public void setTlistService(TlistService tlistService) {
		this.tlistService = tlistService;
	}

	public List<Tlist> getTlists() {
		return tlists;
	}

	public void setTlists(List<Tlist> tlists) {
		this.tlists = tlists;
	}

	public String getTlistName() {
		return tlistName;
	}

	public void setTlistName(String tlistName) {
		this.tlistName = tlistName;
	}

	public List<Task> getTasks() {
		return tasks;
	}

	public void setTasks(List<Task> tasks) {
		this.tasks = tasks;
	}

	public Map<String, Object> getJsonMap() {
		return jsonMap;
	}

	public void setJsonMap(Map<String, Object> jsonMap) {
		this.jsonMap = jsonMap;
	}

	public String getUpdateType() {
		return updateType;
	}

	public void setUpdateType(String updateType) {
		this.updateType = updateType;
	}

	public String getTaskIds() {
		return taskIds;
	}

	public void setTaskIds(String taskIds) {
		this.taskIds = taskIds;
	}

	public String getTaskPriority() {
		return taskPriority;
	}

	public void setTaskPriority(String taskPriority) {
		this.taskPriority = taskPriority;
	}

	public String getUpdateTaskId() {
		return updateTaskId;
	}

	public void setUpdateTaskId(String updateTaskId) {
		this.updateTaskId = updateTaskId;
	}

	public String getUpdateTaskName() {
		return updateTaskName;
	}

	public void setUpdateTaskName(String updateTaskName) {
		this.updateTaskName = updateTaskName;
	}

	public String getUpdateTaskStartTime() {
		return updateTaskStartTime;
	}

	public void setUpdateTaskStartTime(String updateTaskStartTime) {
		this.updateTaskStartTime = updateTaskStartTime;
	}

	public String getTlistId() {
		return tlistId;
	}

	public void setTlistId(String tlistId) {
		this.tlistId = tlistId;
	}

	public JobManager getJobManager() {
		return jobManager;
	}

	public void setJobManager(JobManager jobManager) {
		this.jobManager = jobManager;
	}

	public String getUpdateTaskNote() {
		return updateTaskNote;
	}

	public void setUpdateTaskNote(String updateTaskNote) {
		this.updateTaskNote = updateTaskNote;
	}
	
}
